﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CashOrCard.Models;
using CashOrCard.Helper;

namespace CashOrCard.Controllers
{
    public class SiteController : Controller
    {
        private CashOrCardContext db = new CashOrCardContext();

        // GET: /site/index/5
        public ActionResult Index(int id = 0)
        {
            AdvtSite advtsite = db.AdvtSites.Find(id);           
            if (advtsite == null)
            {
                return HttpNotFound();
            }
            ViewData["categoryList"] = Common.GetSiteTypeList();
            return View(advtsite);
        }

        [HttpPost]
        public JsonResult VisitSite(int siteId)
        {
            if (Request.IsAuthenticated)
            {
                AdvtSite advtsite = db.AdvtSites.Find(siteId);
                if (advtsite != null)
                {
                    if (!string.IsNullOrEmpty(advtsite.SiteURL))
                    {
                        advtsite.SiteAmount = advtsite.SiteAmount - Common.SiteVisitChargeAmount;
                        db.SaveChanges();

                        PaymentHistory ph = new PaymentHistory();
                        ph.PaymentComment = "User Click Visit Site Tab";
                        ph.PaymentDate = DateTime.Now;
                        ph.PaymentAmount = Common.SiteVisitChargeAmount;
                        ph.PaidDate = DateTime.Now;
                        ph.PaymentResult = true;
                        ph.PaymentStatus = "Success";
                        ph.PaymentType = PaymentType.VisitSite.ToString();

                        User user = advtsite.User;// db.Users.Where(x => x.AdvtSites.Contains(advtsite)).First();
                        if (user != null)
                        {
                            ph.UserId = user.UserId;
                            ph.UserEmail = user.Email;
                        }

                        db.PaymentHistorys.Add(ph);
                        db.SaveChanges();
                    }
                    return Json(new { result = "success", errormsg = "", url = advtsite.SiteURL });
                }
                else
                {
                    return Json(new { result = "failed", errormsg = "Error Occurs, Please try" });
                }
            }
            else
            {
                return Json(new { result = "NotAuthenticated", errormsg = "Not Authenticated" });
            }
        }

        [HttpPost]
        public JsonResult SubmitRate(float rate, int siteId)
        {            
            float rateValue = 0F;
            try
            {                
                AdvtSite advtsite = db.AdvtSites.Find(siteId);
                rateValue = advtsite.SiteRate;
                if (advtsite.StarRates.Select(x => x.UserId == Common.CurrentUser.UserId && x.RateDate.Date == DateTime.Now.Date).Count() > 0)
                {
                    return Json(new { result = "failed", errormsg = "You alreay did rate, please rate later", newrate = rateValue });
                }
                else
                {
                    StarRate starRate = new StarRate { Rate = rate, RateDate = DateTime.Now, UserId = Common.CurrentUser.UserId };
                    db.AdvtSites.Find(siteId).StarRates.Add(starRate);
                    db.SaveChanges();
                    ReCalculteRate(siteId, out rateValue);
                    return Json(new { result = "success", errormsg = "", newrate= rateValue});
                }
            }
            catch (Exception ex)
            {
                return Json(new { result = "failed", errormsg = "Error Occurs, Please try", newrate = rateValue });
            }
        }

        private void ReCalculteRate(int siteId, out float newRateValue)
        {
            AdvtSite advtsite = db.AdvtSites.Find(siteId);
            newRateValue = advtsite.StarRates.Sum(x => x.Rate) / advtsite.StarRates.Count;
            advtsite.SiteRate = newRateValue;
            db.SaveChanges();
        }

        
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


    }
}